package com.lalameow.loreattr.attribute.attribute.valueattribute;

import com.lalameow.loreattr.attribute.attribute.AbstractValueAttribute;
import com.lalameow.loreattr.attribute.AttributeManager;
import com.lalameow.loreattr.attribute.entity.EntityAttribute;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.entity.LivingEntity;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: SettingDust
 * Date: 2017/6/28.
 */
public class AttributeAttackSpeed extends AbstractValueAttribute {
    private Pattern attackSpeed = Pattern.compile("[+](\\d+)[ ](" + entityAttribute.getKeyword() + ")");

    public AttributeAttackSpeed() {
        super(EntityAttribute.getAttribute("attack_speed"));
    }


    @Override
    public double getValue(List<String> lore) {
        int speed = 1;
        for (String s : lore) {
            Matcher valueMatcher = attackSpeed.matcher(s.toLowerCase());
            if (valueMatcher.find()) {
                speed += Integer.valueOf(valueMatcher.group(1));
            }
        }
        return speed;
    }

    public void applySpeed(LivingEntity entity) {
        AttributeInstance attribute = entity.getAttribute(Attribute.GENERIC_ATTACK_SPEED);
        for (AttributeModifier attributeModifier : attribute.getModifiers()) {
            if (attributeModifier.getName().equals("loreattr_attack_speed")) {
                attribute.removeModifier(attributeModifier);
            }
        }
        AttributeModifier modifier = new AttributeModifier("loreattr_attack_speed"
                , AttributeManager.attackSpeed.getAttribute(entity)
                , AttributeModifier.Operation.ADD_NUMBER);
        attribute.addModifier(modifier);
    }
}
